// pages/admininfo/admininfo.js
var util = require('../../utils/util.js'); 
Page({

  /**
   * 页面的初始数据
   */
  data: {
    formid: null,

    rentday: null,
    renewday: null, 
    rentnum: null,
    nearbyday: 7
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获得借阅参数
    const db = wx.cloud.database()
    const _ = db.command
    db.collection('RentPara')
      .where
      ({
        rtype: _.eq('图书')
      })
      .get
      ({
        success: res => {
          this.setData(
            {
              rentday: res.data[0].rentDay,
              rentnum: res.data[0].rentNum,
              renewday: res.data[0].renewday,
            }
          )
          console.log('管理员查询成功:', res.data)

        },
        fail: err => {
          wx.showToast({
            icon: 'none',
            title: '查询记录失败'
          })
          console.error('数据库查询失败', err)
        }
      })

    //获取token
    wx.request({
      url: "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential",
      data: {
        appid: getApp().globalData.appID,
        secret: getApp().globalData.appSecret
      },
      success: function (res) {
        console.log('access_token:', res.data.access_token)
        getApp().globalData.access_token = res.data.access_token;
      }
    })
  },


  //借阅设置
  RentSetting: function () {
    wx.navigateTo({
      url: '../rentSetting/rentSetting',
    })
  },

  //信息录入
  JumptoLoad: function () {
    wx.navigateTo({
      url: '../desktop/desktop',
    })

  },

  //生成二维码
  produCode:function(){
    wx.navigateTo({                                   //页面无参数传递跳转
      url: '../qrCode/qrCode',
    })
  },

  //器材借阅申请
  RentDeviceList: function () {
    wx.navigateTo({
    url: '../rentdevicelist/rentdevicelist',
    })
  
  },

  //读书心愿单
  WantedBook: function () {
    // 获取token
    wx.request({
      url: "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential",
      data: {
        appid: getApp().globalData.appID,
        secret: getApp().globalData.appSecret
      },
      success: function (res) {
        console.log('access_token:', res.data.access_token)
        getApp().globalData.access_token = res.data.access_token;
      }
    })
    wx.navigateTo({
      url: '../wantedBook/wantedBook',
    })
  },

  //退出
  warn: function () {
    wx.switchTab({                    //使用switchTab,跳转到 tabBar 页面
      url: '../personal/personal',
    })
  },

  //发送通知
  formSubmit: function (event) {

    console.log('this is formsubmit', event)

    /* 初始化数据库 */
    const db = wx.cloud.database()
    const _ = db.command
    db.collection('Books')
      .get
      ({
        success: res => {
          this.setData({
            arr: res.data
          });

          var brr = this.data.arr
          var blength = this.data.arr.length
          // console.log('666', blength)
          for (var i = 0; i < blength; i++) {
            var length = this.data.arr[i].ownerid.length
            // console.log('666', length)
            for (var j = 0; j < length; j++) {
              var bookname = this.data.arr[i].title
              var hosterid = this.data.arr[i].ownerid[j]
              var hostername = this.data.arr[i].owner[j]
              var renewday = this.data.renewday
              var thisbookrenew = this.data.arr[i].renew[j]
              var rentflag = 0
              if (thisbookrenew == true) { rentflag = 1 }

              if (hosterid != '空') {
                var n_to = this.data.arr[i].rentdate[j] * 1000
                var rent_date = new Date(n_to);
                console.log('rent_date', rent_date)
                var w_temp = this.data.rentday
                var m_to = n_to + 24 * 60 * 60 * 1000 * (w_temp + renewday * thisbookrenew)
                console.log('M-To:', m_to)
                var return_date = new Date(m_to);
                console.log('return_date', return_date)
                var timestamp = Date.parse(new Date());
                var i_to = m_to - timestamp
                var restday = i_to / (24 * 60 * 60 * 1000)
                restday = parseInt(restday)
                console.log('restday', restday)
                if (restday < this.data.nearbyday && restday > 0) {
                  console.log('即将到期')

                  //2.归还通知

                  //准备模版数据
                  console.log('getApp()_token:', getApp().globalData.access_token)
                  let _access_token = getApp().globalData.access_token;
                  let url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + _access_token;
                  let _jsonData = {
                    access_token: _access_token,
                    // touser: 'ow6NN5VmfGWIwdAbO4kiyqMX8Y28',
                    touser: hosterid,
                    template_id: getApp().globalData.bookdead,
                    form_id: event.detail.formId,
                    page: "pages/shelter/shelter",
                    data: {
                      "keyword1": { "value": "《" + bookname + "》", "color": "#173177" },
                      "keyword2": { "value": restday + "天", "color": "#173177" },
                      "keyword3": { "value": util.formatTime(rent_date), "color": "#173177" },
                      "keyword4": { "value": util.formatTime(return_date), "color": "#173177" },
                      "keyword5": { "value": "图书即将到期，请尽快归还。", "color": "#173177" },
                    },
                    //需要放大的关键字
                    // emphasis_keyword: 'keyword1.DATA'
                  }
                  //发送模版消息
                  wx.request({
                    url: url,
                    data: _jsonData,
                    method: 'POST',
                    success: function (res) {
                      console.log(res)
                    },
                    fail: function (err) {
                      console.log('request fail ', err);
                    },
                    complete: function (res) {
                      console.log("request completed!");
                    }

                  })

                  console.log('完成')
                }
                if (restday <= 0) {

                  console.log('超期')
                  //2.超期通知

                  //准备模版数据
                  console.log('getApp()_token:', getApp().globalData.access_token)
                  let _access_token = getApp().globalData.access_token;
                  let url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + _access_token;
                  let _jsonData = {
                    access_token: _access_token,
                    // touser: 'ow6NN5VmfGWIwdAbO4kiyqMX8Y28',
                    touser: hosterid,
                    template_id: getApp().globalData.bookmust,
                    form_id: event.detail.formId,
                    page: "pages/shelter/shelter",
                    data: {
                      "keyword1": { "value": hostername, "color": "#173177" },
                      "keyword2": { "value": "《" + bookname + "》", "color": "#173177" },
                      "keyword3": { "value": util.formatTime(return_date), "color": "#173177" },
                      "keyword4": { "value": "您当前借阅的《" + bookname + "》已经超期，请尽快归还", "color": "#173177" },
                    },
                    //需要放大的关键字
                    // emphasis_keyword: 'keyword1.DATA'
                  }
                  //发送模版消息
                  wx.request({
                    url: url,
                    data: _jsonData,
                    method: 'POST',
                    success: function (res) {
                      console.log(res)
                    },
                    fail: function (err) {
                      console.log('request fail ', err);
                    },
                    complete: function (res) {
                      console.log("request completed!");
                    }

                  })

                  console.log('完成')

                }
              }
            }

          }


          this.setData({
            brr: brr
          })

          console.log('数据库查询成功:', res.data)


        },
        fail: err => {
          wx.showToast({
            icon: 'none',
            title: '查询记录失败'
          })
          console.error('数据库查询失败', err)
        }
      })

  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})